package wechat.util;

import org.apache.http.client.ClientProtocolException;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by Administrator on 2016/3/31.
 */
public class PostFileUtil {
    public static String postFile(String url, File file) throws IOException {
        return postFile(url, file, file.getName(), null);
    }

    public static String postFile(String url, File file, String fileName) throws IOException {
        return postFile(url, file, fileName, null);
    }

    //上传素材（临时素材，永久视频素材，永久其他素材）
    public static String postFile(String url, File file, String fileName, String body) throws IOException {
        if (!file.exists())
            return null;
        return postFile(url, new FileInputStream(file), fileName, body);
    }

    public static String postFile(String url, InputStream inputStream, String fileName) throws IOException {
        return postFile(url, inputStream, fileName, null);
    }

    public static String postFile(String url, InputStream inputStream, String fileName, String body) throws IOException {
        String result = null;
        try {
            URL url1 = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Cache-Control", "no-cache");
            conn.setRequestProperty("Charset", "UTF-8");
            String boundary = "-----------------------------" + System.currentTimeMillis();
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

            OutputStream output = conn.getOutputStream();
            output.write(("--" + boundary + "\r\n").getBytes());
            output.write(String.format("Content-Disposition: form-data;name=\"media\";filename=\""
                    + fileName + "\"\r\n").getBytes());
            if (body != null) {
                output.write("Content-Type: video/mp4 \r\n\r\n".getBytes());
            } else {
                output.write("Content-Type:application/octet-stream\r\n\r\n".getBytes());
            }

            byte[] data = new byte[1024];
            int len = 0;
            InputStream input = inputStream;
            while ((len = input.read(data)) > -1) {
                output.write(data, 0, len);
            }
            if (body != null) {
                output.write(("--" + boundary + "\r\n").getBytes());
                output.write("Content-Disposition: form-data; name=\"description\";\r\n\r\n".getBytes());
                output.write(String.format(body).getBytes());
                output.write(("\r\n--" + boundary + "--\r\n\r\n").getBytes());
            } else {
                output.write(("\r\n--" + boundary + "--\r\n\r\n").getBytes());
            }
            output.flush();
            output.close();
            input.close();
            InputStream resp = conn.getInputStream();
            StringBuffer sb = new StringBuffer();
            while ((len = resp.read(data)) > -1)
                sb.append(new String(data, 0, len, "utf-8"));
            resp.close();
            result = sb.toString();
//            System.out.println(result);
        } catch (ClientProtocolException e) {
        } catch (IOException e) {
        }
        return result;
    }

    public static String postFile(String url, FileInputStream inputStream, String fileName, String body) throws IOException {
        return postFile(url,(InputStream)inputStream,fileName,body);
    }
}
